package com.yunchao.feature.base.domain.utils

import android.content.Context
import android.net.Uri
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.ImageEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.utils.ActivityCompatHelper
import com.luck.picture.lib.utils.DateUtils
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File
import com.yunchao.feature.base.R


/**
 * 选择图片
 */
fun Context.pictureSelectorActivity(block: (LocalMedia) -> Unit) {
    PictureSelector.create(this)
        .openGallery(SelectMimeType.ofAll())
        .setSelectorUIStyle(PictureSelectorStyle())
        .setImageEngine(CustomGlideEngine.instance)
        .setCompressEngine(CustomCompressEngine.instance)
        .isAutoVideoPlay(true)
        .isPageSyncAlbumCount(true)
        .setSelectionMode(SelectModeConfig.SINGLE)
        .isPreviewFullScreenMode(false)
        .isVideoPauseResumePlay(false)
        .isPreviewZoomEffect(true)
        .isPreviewImage(true)
        .isPreviewVideo(true)
        .setMaxSelectNum(1)
        .setMaxVideoSelectNum(1)
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia?>?) {
                result?.get(0)?.apply {
                    block(this)
                }
            }

            override fun onCancel() {
            }
        })

}

/**
 * 预览图片
 */
fun Context.previewPictureSelectorActivity(
    position: Int,
    localMediaList: ArrayList<LocalMedia>
) {
    // 预览图片、视频、音频
    PictureSelector.create(this)
        .openPreview()
        .setImageEngine(CustomGlideEngine.instance)
        .setSelectorUIStyle(PictureSelectorStyle())
        .isAutoVideoPlay(true)
        .isPreviewFullScreenMode(true)
        .isVideoPauseResumePlay(false)
        .isUseSystemVideoPlayer(false)
        .startActivityPreview(position, false, localMediaList)
}

/**
 * 预览图片
 */
fun Fragment.previewPictureSelectorFragment(
    position: Int,
    localMediaList: ArrayList<LocalMedia>?
) {
    // 预览图片、视频、音频
    PictureSelector.create(this)
        .openPreview()
        .setImageEngine(CustomGlideEngine.instance)
        .setSelectorUIStyle(PictureSelectorStyle())
        .isAutoVideoPlay(true)
        .isPreviewFullScreenMode(false)
        .isVideoPauseResumePlay(false)
        .isUseSystemVideoPlayer(true)
        .startFragmentPreview(position, true, localMediaList)
}


/**
 * 选择图片
 */
fun Fragment.pictureSelectorFragment(block: (LocalMedia) -> Unit) {
    PictureSelector.create(this)
        .openGallery(SelectMimeType.ofAll())
        .setSelectorUIStyle(PictureSelectorStyle())
        .setImageEngine(CustomGlideEngine.instance)
        .setCompressEngine(CustomCompressEngine.instance)
        .isAutoVideoPlay(true)
        .isPageSyncAlbumCount(true)
        .setSelectionMode(SelectModeConfig.SINGLE)
        .isPreviewFullScreenMode(false)
        .isVideoPauseResumePlay(false)
        .isPreviewZoomEffect(true)
        .isPreviewImage(true)
        .isPreviewVideo(true)
        .setMaxSelectNum(1)
        .setMaxVideoSelectNum(1)
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia?>?) {
                result?.get(0)?.apply {
                    block(this)
                }
            }

            override fun onCancel() {
            }
        })
}


/**
 *  自定义压缩引擎
 */
class CustomCompressEngine private constructor() : CompressFileEngine {
    override fun onStartCompress(
        context: Context?,
        source: ArrayList<Uri>?,
        call: OnKeyValueResultCallbackListener?
    ) {
        Luban.with(context).load(source).ignoreBy(100).setRenameListener { filePath ->
            filePath?.let {
                val indexOf = it.lastIndexOf(".")
                var postFix = ".jpg"
                if (indexOf != -1) {
                    postFix = it.substring(indexOf)
                }
                DateUtils.getCreateFileName("CMP_") + postFix
            } ?: ""
        }.filter { path ->
            path?.run {
                if (PictureMimeType.isUrlHasImage(this) && !PictureMimeType.isHasHttp(this))
                    true
                else
                    !PictureMimeType.isUrlHasGif(this)
            } == true
        }.setCompressListener(object : OnNewCompressListener {
            override fun onStart() {

            }

            override fun onSuccess(source: String?, compressFile: File?) {
                call?.apply {
                    this.onCallback(source, compressFile?.absolutePath)
                }
            }

            override fun onError(source: String?, e: Throwable?) {
                call?.apply {
                    this.onCallback(source, null)
                }
            }

        }).launch()
    }

    companion object {
        val instance: CustomCompressEngine by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            CustomCompressEngine()
        }
    }
}


class CustomGlideEngine private constructor() : ImageEngine {
    override fun loadImage(context: Context?, url: String?, imageView: ImageView?) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!).load(url).into(imageView!!)
    }

    override fun loadImage(
        context: Context?,
        imageView: ImageView?,
        url: String?,
        maxWidth: Int,
        maxHeight: Int
    ) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!)
            .load(url)
            .override(maxWidth, maxHeight)
            .into(imageView!!)
    }

    override fun loadAlbumCover(context: Context?, url: String?, imageView: ImageView?) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!)
            .asBitmap()
            .load(url)
            .override(180, 180)
            .sizeMultiplier(0.5f)
            .transform(CenterCrop(), RoundedCorners(8))
            .placeholder(R.drawable.default_image_placeholder)
            .into(imageView!!)
    }

    override fun loadGridImage(context: Context?, url: String?, imageView: ImageView?) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!)
            .load(url)
            .override(200, 200)
            .centerCrop()
            .placeholder(R.drawable.default_image_placeholder)
            .into(imageView!!)
    }

    override fun pauseRequests(context: Context?) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!).pauseRequests()
    }

    override fun resumeRequests(context: Context?) {
        if (!ActivityCompatHelper.assertValidRequest(context)) {
            return
        }
        Glide.with(context!!).resumeRequests()
    }

    companion object {
        val instance: CustomGlideEngine by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            CustomGlideEngine()
        }
    }
}